<template>
  <div class="el-container">
    <el-dialog title="添加用户" draggable :model-value="dialogVisible" width="40%" append-to-body @close="close">
      <el-form :model="userInfoForm" label-width="100px" class="form-container">
        <h2 class="form-title">用户注册</h2>
        <el-form-item label="用户名">
          <el-input v-model="userInfoForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="userInfoForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userInfoForm.nickName" placeholder="请输入昵称"></el-input>
        </el-form-item>
<!--        <el-form-item label="用户类型">-->
<!--          <el-select v-model="userInfoForm.type" placeholder="请选择用户类型">-->
<!--            <el-option label="商家" value="商家"></el-option>-->
<!--            <el-option label="平台" value="平台"></el-option>-->
<!--            <el-option label="工程师" value="工程师"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="电子邮件">
          <el-input v-model="userInfoForm.email" placeholder="请输入电子邮件"></el-input>
        </el-form-item>
        <el-form-item class="form-actions">
          <el-button type="primary" @click="save">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { inject, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  dialogVisible: Boolean
})

const $emit = defineEmits(['closeDialog'])

const axios = inject('$axios')
const userInfoForm = reactive({
  userName: '',
  password: '',
  nickName: '',
  type: '用户',
  email: ''
})

const save = async () => {
  try {
    const result = await axios.post('/logic/sysuser/add', userInfoForm)
    if (result.data.code === 200) {
      ElMessage.success('注册成功！请重新登陆')
      close()
    } else {
      ElMessage.error('注册失败：' + result.data.msg)
    }
  } catch (error) {
    ElMessage.error('注册时出错：' + error)
  }
  // if (userInfoForm.type === '商家') {
  //   await axios.post('/logic/shop/add', userInfoForm)
  // }
}

const close = () => {
  userInfoForm.userName = ''
  userInfoForm.password = ''
  userInfoForm.nickName = ''
  // userInfoForm.type = ''
  userInfoForm.email = ''
  $emit('closeDialog')
}

watch(() => props.dialogVisible, (newVal) => {
  if (!newVal) {
    close()
  }
})
</script>

<style scoped>
.el-container {
  padding: 20px;
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.el-dialog {
  border-radius: 12px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-form-item {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item .el-input,
.el-form-item .el-select {
  width: 100%;
}

.form-actions {
  text-align: center;
}
</style>
